﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace MemoDb
{
    public class ObjectsCache
    {
        private readonly IDictionary<Type, IDictionary<object, object>> cache = new Dictionary<Type, IDictionary<object, object>>();

        public object Get(Type type, object id)
        {
            var typeCache = GetTypeCache(type);
            object obj;
            typeCache.TryGetValue(id, out obj);

            return obj;
        }

        private IDictionary<object, object> GetTypeCache(Type type)
        {
            IDictionary<object, object> typeCache;
            if (!cache.TryGetValue(type, out typeCache))
            {
                typeCache = new Dictionary<object, object>();
                cache.Add(type, typeCache);
            }
            return typeCache;
        }

        public void Add(Type type, object id, object obj)
        {
            GetTypeCache(type).Add(id, obj);
        }

        public IEnumerable<object> GetAll()
        {
            return cache.SelectMany(x => x.Value).Select(x => x.Value);
        }

        public void Clear()
        {
            cache.Clear();
        }

        public void Remove(Type type, object id)
        {
            cache[type].Remove(id);
        }
    }
}